from typing import List

class Solution:
    def candy(self, ratings: List[int]) -> int:
        """
        分发糖果算法
        :param ratings: 评分列表
        :return: 最少需要的糖果数
        """
        n = len(ratings)
        # 初始化糖果数组，每个孩子至少1个糖果
        candies = [1] * n
        
        # 从左向右遍历，确保右边评分高的孩子获得更多糖果
        for i in range(1, n):
            if ratings[i] > ratings[i-1]:
                candies[i] = candies[i-1] + 1
        
        # 从右向左遍历，确保左边评分高的孩子获得更多糖果
        for i in range(n-2, -1, -1):
            if ratings[i] > ratings[i+1]:
                candies[i] = max(candies[i], candies[i+1] + 1)
        
        # 返回总糖果数
        return sum(candies) 